package com.yangjiayu.controller;

import com.yangjiayu.base.MinIOConfig;
import com.yangjiayu.base.MinIOUtils;
import com.yangjiayu.grace.result.GraceJSONResult;
import com.yangjiayu.grace.result.ResponseStatusEnum;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Classname FileController
 * @Description TODO
 * @Date 2025/6/19 13:49
 * @Created by YangJiaYu
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private MinIOConfig minIOConfig;

    @PostMapping("/uploadInterviewerImage")
    public GraceJSONResult uploadFile(@RequestParam("file")MultipartFile file) throws Exception {

        // 获得文件原始名称
        String fileName = file.getOriginalFilename();
        if(StringUtils.isBlank(fileName)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }
        fileName = "interviewer/" + dealWithFilename(fileName);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), fileName, file.getInputStream(),true);

        return GraceJSONResult.ok(imageUrl);
    }


    @PostMapping("/uploadInterviewVideo")
    public GraceJSONResult uploadInterviewVideo(@RequestParam("file")MultipartFile file) throws Exception {

        // 获得文件原始名称
        String fileName = file.getOriginalFilename();
        if(StringUtils.isBlank(fileName)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }
        fileName = "interviewerVideo/" + dealWithFilename(fileName);
        String videoUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(), fileName, file.getInputStream(),true);

        return GraceJSONResult.ok(videoUrl);
    }


    private String dealWithoutFilename(String fileName){
        //abc.png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return uuid + suffixName;

    }

    private String dealWithFilename(String fileName){
        //abc.png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String fName = fileName.substring(0,fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return fName + "-" + uuid + suffixName;

    }

}
